import { BASE_URL, TIMEOUT } from "./config.js";

const httpInterceptor = {
  invoke(options) {
    if (!options.url.startsWith("http")) {
      options.url = BASE_URL + options.url;
    }
    options.timeout = TIMEOUT;
    const token = uni.getStorageSync("token");
    if (token) {
      options.header = {
        ...options.header,
        Authorization: `${token}`,
        "Content-Type": "application/json",
      };
    }
  },
};

const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data.result);
          } else {
            handleError(res.data.code, res.data.msg);
            reject(res.data);
          }
        } else {
          handleError(res.statusCode, "请求异常");
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络连接失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

const upload = (options) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      ...options,
      success: (res) => {
        if (res.statusCode === 200) {
          let info = JSON.parse(res.data);
          if (info.code === 200) {
            resolve(info.result);
          } else {
            handleError(info.code, info.msg);
            reject(info);
          }
        } else {
          handleError(res.statusCode, "请求异常");
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络连接失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

const handleError = (code, msg) => {
  if (code == 400) {
    uni.showToast({
      title: msg || "接口错误",
      icon: "none",
    });
  }
};

uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

export const get = (url, data) =>
  request({
    url,
    method: "GET",
    data,
  });
export const post = (url, data) =>
  request({
    url,
    method: "POST",
    data,
  });

export const upload_post = (
  url,
  options = {
    file: undefined,
    filePath: "",
    name: "",
  }
) =>
  upload({
    url,
    method: "POST",
    ...options,
    header: {
      "Content-Type": "application/json",
    },
  });
